﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PC.AzureMultiApp.Core.Models;
using PC.AzureMultiApp.Storage;
using PC.AzureMultiApp.Core.Helpers;

namespace PC.AzureMultiApp.Core.Counters
{
    public static class Counters
    {
        public static IEnumerable<AzureCounterModel> GetCounters(bool onlyLastValue)
        {
            CounterDataSource dataSource = new CounterDataSource();

            var counters = dataSource.GetCounters()
                            .OrderByDescending(c => c.EventDateTime)
                            .Select(c => Conversions.GetCounter(c));

            if (onlyLastValue)
                return counters.Distinct(new CounterComparer());
            else
                return counters;
        }

        public static void Clear()
        {
            CounterDataSource dataSource = new CounterDataSource();
            dataSource.Clear();
        }
    }

    class CounterComparer : IEqualityComparer<AzureCounterModel>
    {
        public bool Equals(AzureCounterModel x, AzureCounterModel y)
        {
            if (Object.ReferenceEquals(x, y)) 
                return true;

            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            return x.RoleInstance == y.RoleInstance && x.CounterName == y.CounterName;
        }


        public int GetHashCode(AzureCounterModel counter)
        {
            if (Object.ReferenceEquals(counter, null)) 
                return 0;

            string hash = String.Format("{0}{1}", counter.RoleInstance, counter.CounterName);

            return hash.GetHashCode();

        }

    }


}
